﻿// -----------------------------------------------------------------------
// <copyright file="EntityExtensions.cs" company="VDC-IT" author="LTDUC">
//      Copyright (c) VDC-IT. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------

namespace VDC.VONE.ENTITIES
{
    using System;
    using System.Reflection;
    
    /// <summary>
    /// Class EntityExtensions
    /// </summary>
    public static class EntityExtensions
    {
        /// <summary>
        /// Create a copy with type of string has trim
        /// </summary>
        /// <typeparam name="T">param type of T</typeparam>
        /// <param name="entityEN">param entityEN</param>
        /// <returns>return T</returns>
        public static T Copy<T>(this EntityEN entityEN)
        {
            var entityCopy = Activator.CreateInstance<T>();

            PropertyInfo[] properties = entityCopy.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo propertyInfo in properties)
            {
                if (propertyInfo.CanRead && propertyInfo.CanWrite)
                {
                    PropertyInfo property = entityEN.GetType().GetProperty(propertyInfo.Name);
                    var value = property.GetValue(entityEN, null);
                    propertyInfo.SetValue(entityCopy, value, null);
                    if (propertyInfo.PropertyType == typeof(string))
                    {
                        propertyInfo.SetValue(entityCopy, string.Format("{0}", value).Trim(), null);
                    }
                }
            }

            return entityCopy;
        }
    }
}
